package jdbcForMe.handler;

import jdbcForMe.mySetting.MyFormSetting;
import jdbcForMe.mySetting.MyItemSetting;
import jdbcForMe.setting.FormSetting;
import jdbcForMe.setting.ItemSetting;

import java.sql.*;

public class DBSelector implements Selector {
    private Connection connection;

    public DBSelector(Connection conn) {
        connection = conn;
    }

    /**
     * 获取指定表的所有数据
     *
     * @param tableName 需要获取的数据表的名字
     * @return 返回一个FormSetting
     * @throws SQLException SQLException
     */
    public FormSetting select(String tableName) throws SQLException {
        String sql = "select * from " + tableName;
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        ItemSetting is = null;
        FormSetting fs = new MyFormSetting();
        while (rs.next()) {
            is = new MyItemSetting<>(rs.getInt(1), rs.getString(2));
            fs.mix(is);
        }
        return fs;
    }

    /**
     * 关闭数据连接流
     *
     * @throws SQLException if a database access error occurs
     */
    @Override
    public void dispose() throws SQLException {
        connection.close();
    }

}
